package com.meeting.order.controller;

import com.meeting.order.common.ResponseResult;
import com.meeting.order.domain.Meeting;
import com.meeting.order.domain.MeetingRoom;
import com.meeting.order.dto.RoomStatusDTO;
import com.meeting.order.service.MeetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.meeting.order.mapper.MeetingRoomMapper;
import com.meeting.order.mapper.MeetingMapper;

@RestController
@RequestMapping("/meetings")
public class MeetingController {

    @Autowired
    private MeetingService meetingService;
    
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;
    
    @Autowired
    private MeetingMapper meetingMapper;

    /**
     * 添加预定记录
     * @param meeting 会议信息
     * @return 预定结果
     */
    @PostMapping("/bookings")
    public ResponseResult<Meeting> addBooking(@RequestBody Meeting meeting){
        try {
            Meeting bookedMeeting = meetingService.addBooking(meeting);
            return ResponseResult.success(bookedMeeting);
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 删除预定记录
     * @param id 会议ID
     * @return 删除结果
     */
    @DeleteMapping("/bookings/{id}")
    public ResponseResult<String> deleteBooking(@PathVariable int id){
        try {
            int result = meetingService.deleteBooking(id);
            if (result > 0) {
                return ResponseResult.success("删除成功");
            } else {
                return ResponseResult.error(500, "删除失败");
            }
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 更新会议预定记录
     * @param id 会议ID
     * @param meeting 会议信息
     * @return 更新结果
     */
    @PutMapping("/bookings/{id}")
    public ResponseResult<String> updateBooking(@PathVariable int id, @RequestBody Meeting meeting){
        try {
            // 检查用户是否尝试修改不允许修改的字段
            if (meeting.getRoomId() != null || meeting.getRoomName() != null ||
                    meeting.getBookerName() != null || meeting.getStartTime() != null ||
                    meeting.getEndTime() != null) {
                return ResponseResult.error(400, "只能修改会议主题和会议状态，其他信息不可修改");
            }
            meeting.setId(id);
            meetingService.updateBooking(meeting);
            return ResponseResult.success("更新成功");
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 查询会议预定记录（单个）
     * @param bookerName 预订人姓名
     * @param roomName 会议室名称
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return 查询结果
     */
    @GetMapping("/booking")
    public ResponseResult<Meeting> findBookingByCondition(
            @RequestParam(required = false) String bookerName,
            @RequestParam(required = false) String roomName,
            @RequestParam(required = false) LocalDateTime startDate,
            @RequestParam(required = false) LocalDateTime endDate){
        try {
            // 参数检查，确保至少有一个查询条件
            if (bookerName == null && roomName == null && startDate == null && endDate == null) {
                return ResponseResult.error(400, "至少需要提供一个查询条件");
            }
            Meeting meeting = meetingService.findBookingByCondition(bookerName, roomName, startDate, endDate);
            if (meeting == null) {
                return ResponseResult.error(404, "未找到符合条件的会议预订记录");
            }
            return ResponseResult.success(meeting);
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 查询会议预定记录（多个）
     * @param bookerName 预订人姓名
     * @param roomName 会议室名称
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return 查询结果
     */
    @GetMapping("/bookings")
    public ResponseResult<List<Meeting>> findBookingsByCondition(
            @RequestParam(required = false) String bookerName,
            @RequestParam(required = false) String roomName,
            @RequestParam(required = false) LocalDateTime startDate,
            @RequestParam(required = false) LocalDateTime endDate){
        try {
            // 参数检查，确保至少有一个查询条件
            if (bookerName == null && roomName == null && startDate == null && endDate == null) {
                return ResponseResult.error(400, "至少需要提供一个查询条件");
            }
            
            List<Meeting> meetings = meetingMapper.findBookingsByCondition(bookerName, roomName, startDate, endDate);
            return ResponseResult.success(meetings);
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 获取所有会议室信息
     * @return 会议室列表
     */
    @GetMapping("/rooms")
    public ResponseResult<List<MeetingRoom>> getAllMeetingRooms() {
        try {
            List<MeetingRoom> meetingRooms = meetingRoomMapper.findAllMeetingRooms();
            return ResponseResult.success(meetingRooms);
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 获取本周会议室预订统计信息
     * @return 统计信息
     */
    @GetMapping("/statistics/weekly")
    public ResponseResult<Map<String, Object>> getWeeklyStatistics() {
        try {
            // 计算本周开始和结束时间
            LocalDate today = LocalDate.now();
            LocalDateTime weekStart = today.minusDays(today.getDayOfWeek().getValue() - 1).atStartOfDay();
            LocalDateTime weekEnd = weekStart.plusDays(6).withHour(23).withMinute(59).withSecond(59);
            
            // 从数据库查询统计数据
            List<Meeting> meetings = meetingMapper.findMeetingsInDateRange(weekStart, weekEnd);
            
            // 准备统计数据
            Map<String, Object> statistics = new HashMap<>();
            // 按会议室统计
            Map<String, Integer> roomStats = new HashMap<>();
            // 按日期统计
            Map<String, Integer> dailyStats = new HashMap<>();
            
            // 初始化每日统计数据
            for (int i = 0; i < 7; i++) {
                LocalDate date = weekStart.toLocalDate().plusDays(i);
                dailyStats.put(date.toString(), 0);
            }
            
            // 统计数据
            for (Meeting meeting : meetings) {
                // 按会议室统计
                String roomName = meeting.getRoomName();
                roomStats.put(roomName, roomStats.getOrDefault(roomName, 0) + 1);
                
                // 按日期统计
                String dateStr = meeting.getStartTime().toLocalDate().toString();
                dailyStats.put(dateStr, dailyStats.getOrDefault(dateStr, 0) + 1);
            }
            
            statistics.put("roomStats", roomStats);
            statistics.put("dailyStats", dailyStats);
            
            // 返回统计数据
            return ResponseResult.success(statistics);
        } catch (RuntimeException e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
    
    /**
     * 查询会议室在指定时间段的状态
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 会议室状态列表
     */
    @GetMapping("/rooms/status")
    public ResponseResult<List<RoomStatusDTO>> getRoomStatusByTime(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        try {
            // 解析时间参数
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime, formatter) : LocalDateTime.now();
            LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime, formatter) : start.plusHours(1);
            
            // 参数验证
            if (end.isBefore(start)) {
                return ResponseResult.error(400, "结束时间不能早于开始时间");
            }
            
            // 查询会议室状态
            List<RoomStatusDTO> roomStatusList = meetingService.getRoomStatusByTime(start, end);
            return ResponseResult.success(roomStatusList);
        } catch (Exception e) {
            return ResponseResult.error(500, e.getMessage());
        }
    }
}